package cn.org.cute.ebocy.pf.platformservices;

import java.io.IOException;
import java.util.*;
import org.json.JSONArray;
import org.json.JSONObject;
import com.xiaonei.api.*;

import cn.org.cute.ebocy.config.Config;
import cn.org.cute.ebocy.config.Param;
import cn.org.cute.ebocy.util.JsonUtil;
import cn.org.cute.ebocy.util.NormalUtil;
import cn.org.cute.ebocy.util.OpenConfig;
import cn.org.cute.security.domain.*;

/**
 * renren平台的基本api处理
 * @Copyright©2011, 2011 EBO CHANGYOU Co.td. All rights reserved.
 * @Version 1.0.0
 * @since jdk1.6
 * @author xiaolei
 * @date 2011-12-13
 */

public class RenRenPlatformDoingImpl{
	
	//设置用户信息的属性	
	public static EnumSet<ProfileField> userFields = EnumSet.noneOf(ProfileField.class);
	static{
		userFields.add(ProfileField.NAME);
		userFields.add(ProfileField.SEX);
		userFields.add(ProfileField.STAR);
		userFields.add(ProfileField.ZIDOU);
		userFields.add(ProfileField.BIRTHDAY);
		userFields.add(ProfileField.HEADURL);
		userFields.add(ProfileField.HOMETOWN_LOCATION);
	}
	
	//好友信息属性
	public static EnumSet<ProfileField> friendFields = EnumSet.noneOf(ProfileField.class);
	static{
		friendFields.add(ProfileField.NAME);
		friendFields.add(ProfileField.HEADURL);
	}
	
	
	/**获取一个用户的用户信息
	 * 根据指定参数，从renren的api服务器去获得获得平台上去一个用户的用户信息
	 * @return 返回一个平台用户信息
	 *  参考http://wiki.dev.renren.com/wiki/Users.getInfo
	 */
	public PlatformUser getUsersProfile(HashMap<String,String> paramsMap){
		 PlatformUser userProfile = null;
			String pfId = paramsMap.get(Param.ParamName.UID.getName());
			String sessionKey = paramsMap.get(Param.ParamName.AUTH_TOKEN.getName());		
			
			if(NormalUtil.isNull(pfId) || NormalUtil.isNull(sessionKey) ){
			  	return userProfile;
			}
			
		try {
			
			XiaoneiRestClient client = connectToPlatform(sessionKey,Config.getApiKey(),Config.getSecretKey());// 和平台建立通信
			if(client == null){
				return userProfile;
			}
			
			// 用户个人信息
		   String usersInfo = client.users_getInfo(Integer.parseInt(pfId),userFields);
	       JSONArray jsonArray = JsonUtil.getJSONArray(usersInfo);
		    if(jsonArray == null || jsonArray.length() == 0 ){
		    	return userProfile;
		    }
		    
		    userProfile = this.getPlatformUser(userProfile, jsonArray.getJSONObject(0));		    
		    
		    return userProfile;

		} catch (Exception e) {
			//e.printStackTrace();
			return null;
		}	
	}
	
	
	
	/**获取多个用户的信息
	 * 根据指定参数，从renren的api服务器去获得获得平台上>=1个用户信息
	 * @return 返回一个平台用户信息
	 * 参考http://wiki.dev.renren.com/wiki/Users.getInfo
	 */
	public List<PlatformUser> getUsersProfiles(HashMap<String,String> paramsMap){
		 List<PlatformUser> userProfiles = null;
		 
		 String pfId = (String)paramsMap.get(Param.ParamName.UID.getName());
		 String sessionKey = (String)paramsMap.get(Param.ParamName.AUTH_TOKEN.getName());
		 String uids = (String)paramsMap.get(Param.ParamName.UIDS.getName());
		 String isFriendInfo = paramsMap.get(Param.ParamName.ISFRIENDINFO.getName());
		 
		 List<Integer> ids = new ArrayList<Integer>();
		 String [] uid = uids.split(",");
		 for(int i = 0;i<uid.length;i++){
			 if(i>=20&&NormalUtil.isNull(isFriendInfo)){
				 break;
			 }
			 ids.add(Integer.valueOf(uid[i].trim()));
		 }
		 
		 
		   if( NormalUtil.isNull(sessionKey) || ids == null || ids.size() == 0 ){
			   return userProfiles;
		   }
			
		try {
			// 获得当前登录的UId
			XiaoneiRestClient client = connectToPlatform(sessionKey,Config.getApiKey(),Config.getSecretKey());// 和平台建立通信
			if(client == null){
				return userProfiles;
			}		

			// 用户个人信息
		   String usersInfo = client.users_getInfo(ids, userFields);
		   JSONArray jsonArray = JsonUtil.getJSONArray(usersInfo);
		    if(jsonArray == null || jsonArray.length() == 0 ){
		    	return userProfiles;
		    }
		    
		    userProfiles = new ArrayList();
		    for(int i=0;i< jsonArray.length();i++){
		    PlatformUser userProfile = null;
		    JSONObject userObject = jsonArray.getJSONObject(i);
		    userProfile = this.getPlatformUser(userProfile, userObject);
		    if(userProfile != null){
		    	userProfiles.add(userProfile);
		    }

		}
		    return userProfiles;

		} catch (Exception e) {
			//e.printStackTrace();
			return null;
		}	
	}
	
	
	
	/**
	 * 獲取添加應用的好友信息，
	 * @param ifHaveProperty 是否需要獲取好友是屬性，true：會取得好友的name,pic,默認只取好友的ID
	 * @return
	 * @throws Exception
	 *参考地址：http://wiki.dev.renren.com/wiki/Friends.getAppFriends
	 */
	public List<PlatformUser> getAppFriendsInfo(HashMap<String,String> paramsMap){
		List<PlatformUser> appFriendsList = null;
		String pfId = paramsMap.get(Param.ParamName.UID.getName());
		String sessionKey = paramsMap.get(Param.ParamName.AUTH_TOKEN.getName());
		String needDetail = paramsMap.get(Param.ParamName.INFOED.getName());
		if (NormalUtil.isNull(sessionKey)) {
			return appFriendsList;
		}

		try {
			XiaoneiRestClient client = connectToPlatform(sessionKey,Config.getApiKey(),Config.getSecretKey());// 和平台建立通信
			if (client == null) {
				return appFriendsList;
			}
			if ("1".equals(needDetail)) {// 需要获取玩家属性
				String appFriendInfo = client.friends_getAppFriends(this.friendFields);
				JSONArray jsonArray = JsonUtil.getJSONArray(appFriendInfo);
				if (jsonArray == null || jsonArray.length() == 0) {
					return appFriendsList;
				}

				appFriendsList = new ArrayList();
				for (int i = 0; i < jsonArray.length(); i++) {
					PlatformUser userProfile = null;
					JSONObject userObject = jsonArray.getJSONObject(i);
					userProfile = this.getPlatformFriend(userProfile, userObject);
					if (userProfile != null) {
						appFriendsList.add(userProfile);
					}
				}
			} else {// 只返回好友ID
				String appFriendInfo = client.friends_getAppFriends();
				JSONArray jsonArray = JsonUtil.getJSONArray(appFriendInfo);

				if (jsonArray == null || jsonArray.length() == 0) {
					return appFriendsList;
				}

				appFriendsList = new ArrayList();
				for (int i = 0; i < jsonArray.length(); i++) {
					String friendId = jsonArray.getString(i);
					PlatformUser userProfile = new PlatformUser();
					userProfile.setPfId(friendId);
					appFriendsList.add(userProfile);

				}
			}
			return appFriendsList;

		} catch (Exception e) {
			// e.printStackTrace();
			return null;
		}	
		
	}
	
	/**
	 * 获取所有的朋友<br>
	 * @return<br>
	 * 平台uid=platformUser.getPfId();<br>
     * 用户头像=platformUser.getPfMainurl();<br>
     * 平台用户姓名=platformUser.getPfName();<br>
     * 具体的请参考PlatformUser对象<br>
	 * @throws Exception<br>
	 * 参考地址：http://wiki.dev.renren.com/wiki/Friends.getFriends
	 */
	public List<PlatformUser> getFriendsInfo(HashMap<String,String> paramsMap){
		List<PlatformUser> friendsList = null;
		String pfId = paramsMap.get(Param.ParamName.UID.getName());
		String sessionKey = paramsMap.get(Param.ParamName.AUTH_TOKEN.getName());
		String apiKey = paramsMap.get(Param.ParamName.API_KEY.getName());
		String secretKey = paramsMap.get(Param.ParamName.SECRET_KEY.getName());
		
		if (NormalUtil.isNull(sessionKey)) {
			return friendsList;
		}

		try {
			XiaoneiRestClient client = connectToPlatform(sessionKey,apiKey,secretKey);// 和平台建立通信
			if (client == null) {
				return friendsList;
			}
			// 添加应用好友信息
			String friendInfo = client.friends_getFriends();
			JSONArray jsonArray = JsonUtil.getJSONArray(friendInfo);
			if (jsonArray == null || jsonArray.length() == 0) {
				return friendsList;
			}

			friendsList = new ArrayList();
			for (int i = 0; i < jsonArray.length(); i++) {
				PlatformUser userProfile = null;
				JSONObject userObject = jsonArray.getJSONObject(i);
				userProfile = this.getPlatformFriend(userProfile, userObject);
				if (userProfile != null) {
					friendsList.add(userProfile);
				}

			}
			System.out.println(friendsList.size());
			return friendsList;

		} catch (Exception e) {
			// e.printStackTrace();
			return null;
		}
	}
	
	
	/**
	 * 通过user对象转化为PlatformUser对象
	 * 
	 * @return
	 */
	public PlatformUser getPlatformUser(PlatformUser userProfile, JSONObject userObject){
		if (userObject == null) {
			return userProfile;
		}

		if (userProfile == null) {
			userProfile = new PlatformUser();
		}

		userProfile.setPfId(userObject.optString(Param.ParamName.UID.getName()));
		userProfile.setPfName(userObject.optString(Param.ParamName.NAME.getName()));

		// 性别处理
		String sex = "0";
		if (userObject.has("sex")) {
			sex = userObject.optString("sex");
			if (sex == null || "".equals(sex) || "2".equals(sex) || "男".equals(sex)) {
				sex = "1";
			}
		}
		userProfile.setPfSex(sex);

		String mainPic = null;
		if (userObject.has("headurl")) {
			mainPic = userObject.optString("headurl");
		}
		// 图片处理
		if (mainPic == null || "".equals(mainPic) || "null".equals(mainPic)) {
			mainPic = OpenConfig.getInstance().getImageHostUrl() + "women_head.gif";
			if ("1".equals(sex)) {
				mainPic = OpenConfig.getInstance().getImageHostUrl() + "men_head.gif";
			}
		}

		userProfile.setPfHeadurl(mainPic);
		userProfile.setPfMainurl(mainPic);
		userProfile.setPfTinyurl(mainPic);

		String [] statuses = {" "," "," "," "," "," "," "};
		// <star>
		// 表示是否为星级用户，校内中值1表示是；值0表示不是,开心中0表示非真实姓名和头像，1表示非真实姓名，2表示非真实头像，3表示真实用户
		if (userObject.has("star")) {
			String star = userObject.optString("star");
			if (star != null) {
				statuses[3] = star;
			}
		}

		// 表示是否为vip用户，值1表示是；值0表示不是
		if (userObject.has("zidou")) {
			String zidou = userObject.optString("zidou");
			if (zidou != null) {
				statuses[0] = zidou;
			}
		}
		
		StringBuffer status = new StringBuffer();
		for(String s : statuses){
			status.append(s).append(",");
		}
		
		userProfile.setPfStatus(status.toString());

		if (userObject.has("birthday")) {
			String birthday = userObject.optString("birthday");
			if (!NormalUtil.isNull(birthday) && birthday.indexOf("0000-00-00") < 0) {
				userProfile.setPfBirthday(birthday);
			}
		}

		// 家乡处理
		if (userObject.has("hometown_location")) {
			JSONObject hometownObject = userObject.optJSONObject("hometown_location");
			if (hometownObject != null) {
				StringBuffer countrySb = new StringBuffer();
				if (hometownObject.has("country")) {
					String country = hometownObject.optString("country");
					if (!NormalUtil.isNull(country)) {
						countrySb.append(country);
					}
				}
				
				if (hometownObject.has("province")) {
					String province = hometownObject.optString("province");
					if (!NormalUtil.isNull(province)) {
						countrySb.append("#@#");
						countrySb.append(province);
					}
				}

				if (hometownObject.has("city")) {
					String city = hometownObject.optString("city");
					if (!NormalUtil.isNull(city)) {
						countrySb.append("#@#");
						countrySb.append(city);
					}
				}
				userProfile.setPfCountry(countrySb.toString());
				
			}
		}
	    
	    return userProfile;
		
		
	}
	
	
	
	/**
	 * 通过user对象转化为PlatformUser对象
	 * @return
	 */
	public PlatformUser getPlatformFriend(PlatformUser userProfile,JSONObject userObject){
		if(userObject == null){
			return userProfile;
		}
		
		if(userProfile == null){
			userProfile = new PlatformUser();
		}
		
		userProfile.setPfId(userObject.optString("id"));
	    userProfile.setPfName(userObject.optString("name"));
	    
	    //性别处理
	    String sex = "0";
	    if(userObject.has("sex")){
	     sex = userObject.optString("sex");
	    if(sex == null || "".equals(sex) || "2".equals(sex)){
	    	sex = "1";
	    }
	    }
	    userProfile.setPfSex(sex);
	    
	    String mainPic = null;
	    if(userObject.has("headurl")){
	     mainPic = userObject.optString("headurl");	   
	    }
	    //图片处理
	    if(mainPic == null || "".equals(mainPic) || "null".equals(mainPic)){
	    	mainPic = OpenConfig.getInstance().getImageHostUrl()+"women_head.gif";
	    	if("1".equals(sex)){
	    	mainPic = OpenConfig.getInstance().getImageHostUrl()+"men_head.gif";
	    	}
	    }
	    
	    userProfile.setPfHeadurl(mainPic);
	    userProfile.setPfMainurl(mainPic);
	    userProfile.setPfTinyurl(mainPic);
	 
	    
	    return userProfile;
		
		
	}
	
	
	/**
	 * 和平台建立通信连接
	 * @return
	 */
	public XiaoneiRestClient connectToPlatform(String sessionKey,String apiKey,String secretKey){
		XiaoneiRestClient  client = null;
		//String secretKey = UtilTool.getMD5ofStr(GameConfig.getInstance().getSecertkey());// secretKey需要Md5加密
		
		if(NormalUtil.isNull(sessionKey)){
			return client;
		}

		try {
			sessionKey = java.net.URLEncoder.encode(sessionKey, "UTF-8");// sessionKey需要utf-8编码
		} catch (Exception e) {
			return client;
		}
		
	    client = new XiaoneiRestClient(apiKey,secretKey, sessionKey,"JSON");//和校内/开心建立通信连接	
			 

		return client;
		
	}
		
	
	
	/**
	 * 每个app的每一个安装用户(sender)每一天有一定配额 默认配额数量为20条  接收者（receiver）必须是用户的好友或者是安装应用的用户。 
	 * 
	 * 发送通知  
	 * @param notification 通知内容  可以是XNML类型的文本信息，支持的XNML有<xn:name/>和<a/>  如:<a href="http://www.tudou.com/programs/view/Tzpw9PIj8zM/">狮子王</a>
	 * @param to_pfId   to_pfId格式 用户id的列表，单个或多个，可以是逗号分隔，
	 *                 如 8055,8066,8077(小于20个)，
	 * @return
	 * @throws XiaoneiException
	 * @throws IOException
	 */
	public void postMessage(HashMap<String,Object> paramsMap) {
		//do something
		 String sessionKey = (String)paramsMap.get("pfSessionKey");
		 String notification = (String)paramsMap.get("notification");
		 String apiKey = (String)paramsMap.get(Param.ParamName.API_KEY.getName());
		 String secretKey = (String)paramsMap.get(Param.ParamName.SECRET_KEY.getName());
		 
		 String to_ids = (String)paramsMap.get("to_pfId");
		XiaoneiRestClient client = connectToPlatform(sessionKey,apiKey,secretKey);// 和平台建立通信
		if(client == null){
			return;
		}
		try {
			client.notifications_send(notification,to_ids);
		} catch (Exception e) {
			e.printStackTrace();
		}
		
	}	
    
	
	/**
	 *  发送新鲜事<br>
	 * @param feedId ：新鲜事Id<br>
	 * @param bodyArgs ：新鲜事boby参数数组<br>
	 * @param resultMap：返回给flash的map<br>
	 * 参考http://wiki.dev.renren.com/wiki/%E8%87%AA%E5%AE%9A%E4%B9%89%E6%96%B0%E9%B2%9C%E4%BA%8B
	 */
	public void postFeed(String feedId,String picName,String[] bodyArgs,String bodyIntelStr,HashMap resultMap,HashMap paramMap){
		if(resultMap!=null){			
			HashMap feedMap=new HashMap();
			feedMap.put("title", feedId);
			//feedMap.put("image", imageFileName);//暂时在js定义
			feedMap.put("args", bodyArgs);
			resultMap.put("XINXIANSHI", feedMap);
		}
	}
	
	
	  /**
	 *  通过平台注册订单
	 *  @param sessionKey 
	 *  @param order_id 订单ID
	 *  @param amount 消费的钱数
	 *  @param desc 商品描述信息
	 */
	public String regOrder(HashMap<String,Object> paramsMap){
		String payToken = null;
		String pfId = (String)paramsMap.get("pfId");
		String sessionKey = (String)paramsMap.get("pfSessionKey");
		String apiKey = (String)paramsMap.get(Param.ParamName.API_KEY.getName());
		String secretKey = (String)paramsMap.get(Param.ParamName.SECRET_KEY.getName());
		String  order_id = (String)paramsMap.get("order_id");
		int amount = (Integer)paramsMap.get("amount");
		String desc = (String)paramsMap.get("desc");

		XiaoneiRestClient client = connectToPlatform(sessionKey,apiKey,secretKey);// 和平台建立通信
		if(client == null){
			return payToken;
		}		
	
	try {
		  String tokenInfo = client.pay_regOrder(new Long(order_id), amount, desc);
		  JSONObject jsonObject = JsonUtil.getJSONObject(tokenInfo);
		  if(jsonObject == null){
			  return payToken;
		  }
	  
	payToken = jsonObject.getString("token");
	}catch (Exception e) {
	   return payToken;
	}
	return payToken;		
		
	}
	
	/**
	 *  查询订单是否完成
	 *  @param sessionKey 
	 *  @param order_id 订单ID
	 */
	public boolean payIsCompleted(HashMap<String,String> paramsMap){
		
		 String pfId = (String)paramsMap.get("pfId");
		 String sessionKey = (String)paramsMap.get("pfSessionKey");
		String  order_id = (String)paramsMap.get("order_id");
		String apiKey = (String)paramsMap.get(Param.ParamName.API_KEY.getName());
		String secretKey = (String)paramsMap.get(Param.ParamName.SECRET_KEY.getName());
		XiaoneiRestClient client = connectToPlatform(sessionKey,apiKey,secretKey);// 和平台建立通信
		if(client == null){
			return false;
		}
		try{
			return client.pay_isCompleted(new Long(order_id));	
		}catch(Exception e){
			return false;
			
		}
		
	}
	
	/**
	 *  据站外邀请invite_token 得到此次邀请的详细信息（包括邀请者、邀请时间、被邀请者、安装时间等）
	 *  @param sessionKey 
	 *  @param invite_ids 逗号分割的invite_token串
	 *  http://appdev.myspace.cn/wiki/invitations.getOsInfo
	 *  [{ "inviter_uid":1300000000, "invite_time":"2009-01-01 17:16:20","invitee_uid":1300000002,"install_time","2009-01-01 17:16:20"}]
	 *  <inviter_uid>发起邀请的用户ID  <invite_time>邀请时间 (当前等于注册后激活时间) <invitee_uid>接受邀请的新用户ID<install_time>加入游戏时间 (当前等于注册后激活时
	 */
//	public JSONArray getOsInfo(String sessionKey,String invite_ids){
//		JSONArray osInfoArray = null;
//		XiaoneiRestClient client = connectToPlatform(sessionKey);// 和平台建立通信
//		if(client == null){
//			return osInfoArray;
//		}
//		if(invite_ids == null || "".equals(invite_ids)){
//			return osInfoArray;
//		}
//		String[] opArr = invite_ids.split(",");
//		List osList = new ArrayList();
//		for(String ids:opArr){
//			osList.add(ids);
//		}
//		try{
//		  String osInfo = client.invitations_getOsInfo(osList);
//		  osInfoArray = UtilTool.fromartToJsonArray(osInfo);
//		}catch(Exception e){
//			return osInfoArray;
//			
//		}
//		
//		return osInfoArray;
//	}
    
    /**
     * 根据用户的ID获取某个用户站外邀请的详细信息（邀请成功数量）。
     * @param sessionKey
     * @param uids 逗号分割的用户ID
     * @return [{ Param.ParamName.UID.getName():1300000000, "os_invite_total",11}] <uid>用户ID<os_invite_total>成功邀请的用户数
     * http://appdev.myspace.cn/wiki/invitations.getUserOsInviteCnt 
     */
//  public JSONArray getUserOsInviteCnt(String sessionKey,String uids){
//		JSONArray osInviteArray = null;
//		XiaoneiRestClient client = connectToPlatform(sessionKey);// 和平台建立通信
//		if(client == null){
//			return osInviteArray;
//		}
//		if(uids == null || "".equals(uids)){
//			return osInviteArray;
//		}
//		String[] opArr = uids.split(",");
//		List osList = new ArrayList();
//		for(String ids:opArr){
//			osList.add(ids);
//		}
//		try{
//		  String osInfo = client.invitations_getUserOsInviteCnt(osList);
//		  osInviteArray = UtilTool.fromartToJsonArray(osInfo);
//		}catch(Exception e){
//			return osInviteArray;
//			
//		}
//		
//		return osInviteArray;
//	} 
  
  /**
   * 获得当前登录用户的uid
   * @param client
   * @param paramsMap
   * @return uid
   */
  public long getLoggedInUser(HashMap<String,String> paramsMap){
	  long uid = 0;
	  String sessionKey = paramsMap.get(Param.ParamName.AUTH_TOKEN.getName());
	  String apiKey = paramsMap.get(Param.ParamName.API_KEY.getName());
	  String secretKey = paramsMap.get(Param.ParamName.SECRET_KEY.getName());
	
	  XiaoneiRestClient client = connectToPlatform(sessionKey,apiKey,secretKey);// 和平台建立通信
	  if(client != null){
		  try {
			  uid = client.users_getLoggedInUser();		
		  } catch (Exception e) {
			  
		  }
	  }
	  return uid;
  }
  
	/**
	 *  判断用户是不是某个公共主页的粉丝
	 *  @param uid 用户UID 
	 *  @param page_id 公共主页ID，不填写/0 默认为当前应用的公共主页
	 */
	public boolean page_isFans(HashMap<String,String> paramsMap){
		int uid = Integer.parseInt(paramsMap.get(Param.ParamName.UID.getName()));
		int page_id = Integer.parseInt(paramsMap.get("page_id"));
		String sessionKey = paramsMap.get(Param.ParamName.AUTH_TOKEN.getName());
		String apiKey = paramsMap.get(Param.ParamName.API_KEY.getName());
		String secretKey = paramsMap.get(Param.ParamName.SECRET_KEY.getName());
		
		XiaoneiRestClient client = connectToPlatform(sessionKey,apiKey,secretKey);// 和平台建立通信
		if(client == null){
			return false;
		}
		
		
		try{
			return client.page_isfans(uid, page_id);	
		}catch(Exception e){
			return false;
			
		}
		
	}
	
	/**
	 *  判断用是不是添加了应用
	 *  @param uid 用户UID 
	 *  @param page_id 公共主页ID，不填写/0 默认为当前应用的公共主页
	 */
	public boolean getIsAppUser(HashMap<String,String> paramsMap){
		int uid = Integer.parseInt(paramsMap.get(Param.ParamName.UID.getName()));
		String sessionKey = paramsMap.get(Param.ParamName.AUTH_TOKEN.getName());
		String apiKey = paramsMap.get(Param.ParamName.API_KEY.getName());
		String secretKey = paramsMap.get(Param.ParamName.SECRET_KEY.getName());
		
		XiaoneiRestClient client = connectToPlatform(sessionKey,apiKey,secretKey);// 和平台建立通信
		if(client == null){
			return false;
		}
		
		try{
			if(uid == 0){
				return client.users_isAppAdded();
			} else {
				return client.users_isAppAdded(uid);
			}
		}catch(Exception e){
			return false;
			
		}
		
	}
  
}